package br.com.galluzzo.operators;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.util.HttpURLConnection;

import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.sparql.engine.http.HttpContentType;

@Path("merge")
public class MergeResource {
	
	
	public String executar( String URIs) {
		try {
			Model m = null;
			String[] urls = URIs.split(",");
			for (String url : urls) {

				URL u = new URL(url);
				HttpContentType ct = new HttpContentType(u.getPath());
				System.out.println(ct.getMediaType());
				
				BufferedReader br = new BufferedReader(new InputStreamReader(
						u.openStream()));
				Model model = ModelFactory.createDefaultModel();
				
				model.read(br,u.getPath());
				if(m == null) {
					m = model;
				} else {
					m = ModelFactory.createUnion(m, model);
				}
				
			}
			
			/*StmtIterator iter = m.listStatements();
			
			String retorno = "Subject - Predicate - Objeto\n";
			while (iter.hasNext()) {
				Statement st = iter.nextStatement();
				retorno += st.getSubject() + " - " + st.getPredicate() + " - "
						+ st.getObject() + "\n";
			}
			retorno +="------------------------------------------------";*/
			
			StringWriter sw = new StringWriter();
			m.write(sw);
			return sw.toString();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
		
	}
	@GET
	@Path("json")
	@Produces(MediaType.APPLICATION_JSON)
	public String produzJson(@QueryParam("uris") String URIs){
		return executar(URIs);
	}
	
	@GET
	@Path("xml")
	@Produces(MediaType.APPLICATION_XML)
	public String produzXML(@QueryParam("uris") String URIs){
		return executar(URIs);
	}
	
}
